// pages/my/my.js
var common = require("../../utils/public.js") //引入public.js脚本
var api = require("../../utils/api");
var time = require("../../utils/time.js");
import regeneratorRuntime from '../../utils/runtime/runtime.js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    discountNum: '',
    vipFlag: '',
    isInit: false,
    getStatus: [],
    shopBack: [],
    codeNum: "",
    //默认店名
    storeName: "",
    userMessage: '',
    //城市
    city: '',
    //微信头像
    avatarUrl: '',
    //省份
    province: '',
    //性别
    gender: '',
    //微信名字
    nickName: '',
    storeChoose: '',
    codeNum: '',
    tokenCode: '',
    name: 10,
    // 订单分类 数量
    // count: {status:"",obligation:"",distribution:"",shipped:"",received:""}
    count: "",
    status: null,
    btnOrder: [{
        name: '待付款',
        url: '../../images/my_icon_01.png',
        id: 0,
      },
      {
        name: '待配送',
        url: '../../images/my_icon_02.png',
        id: 1,

      },
      {
        name: '已发货',
        url: '../../images/my_icon_03.png',
        id: 2,

      },
      {
        name: '已收货',
        url: '../../images/my_icon_04.png',
        id: 4,

      },
      {
        name: '退换/售后',
        url: '../../images/my_icon_05.png',
      }
    ],
    num: [{
        num: 1
      },
      {
        num: 5
      },
      {
        num: 5
      },
      {
        num: 51
      }
    ],
    //用户信息
    userMess: '',

    //当前状态
    type: ''
  },


  onLoad: function (e) {

    let that = this
    if (JSON.stringify(e) == "{}") {
      // 切换个人商家
      that.setData({
        type: wx.getStorageSync("type")
      })
    } else {
      console.log(e)
      let url = e.q;
      let params = url.split("%3D");
      let userId = params[params.length - 1].split("%26")[0];
      let type = params[params.length - 2].split("%26")[0];

      if (type == 1) {

        wx.setStorageSync("userId", userId)

        if (wx.getStorageSync("token") == "") {

          wx.reLaunch({
            url: '../userMess/userMess',
          })
        } else {
          //这个人已经登陆了
          if (wx.getStorageSync("codeNum") == 99) {
            console.log(wx.getStorageSync("userMess").id, userId)
            api.empower({
              grantUserId: userId,
              userId: wx.getStorageSync("userMess").id,
            }).then(res => {
              if (res.code) {
                wx.showToast({
                  title: res.msg,
                  icon: 'none'
                })
                return
              }
              if (res.result) {
                wx.showToast({
                  title: '店铺授权成功',
                  icon: 'none'
                })
              } else {
                wx.showToast({
                  title: '网络出现问题，稍后重试',
                  icon: 'none'
                })
              }


            })
          } else {
            //店铺不行
            wx.showToast({
              title: '该用户注册尚未完善',
              icon: 'none'
            })

          }
        }
      }
    }

  },
  // 商家个人切换 
  xzmd: common.throttleFunc(function (e) {
    wx.navigateTo({
      url: '/pages/xzmd/xzmd',
    })
  }),
  // 跳转钱包
  wallet: common.throttleFunc(function (e) {
    wx.navigateTo({
      url: '/pages/wallet/wallet',
    })
  }),
  // 跳转积分
  jifen: common.throttleFunc(function (e) {

    wx.navigateTo({
      url: '/pages/jifen/jifen?score=' + this.data.userMess.score,
    })
  }),
  // 跳转优惠券
  yhq: common.throttleFunc(function (e) {

    wx.navigateTo({
      url: '/pages/yhq/yhq',
    })
  }),

  //跳转
  addUser: common.throttleFunc(function (e) {
    if (this.data.type == 1) {
      wx.navigateTo({
        url: '/pages/add_qx/add_qx',
      })
    }
  }),

  // 跳转我的订单
  my_order: common.throttleFunc(function (e) {
    let index = 0
    if (e.currentTarget.dataset.index == 0) {
      index = 1
    } else if (e.currentTarget.dataset.index == 1) {
      index = 2
    } else if (e.currentTarget.dataset.index == 2) {
      index = 3
    } else if (e.currentTarget.dataset.index == 3) {
      index = 5
    } else if (e.currentTarget.dataset.index == 4) {
      index = 8
    }

    wx.navigateTo({
      url: '/pages/myOrder/myOrder?index=' + index,
    })
  }),
  // 跳转地址管理
  address: common.throttleFunc(function (e) {
    if (wx.getStorageSync("type") == 1) {
      console.log(this.data.isType)
      wx.navigateTo({
        url: '/pages/address/address',
      })
    } else {
      wx.navigateTo({
        url: '/pages/personAddress/personAddress',
      })
    }
  }),
  // 跳转提报需求
  tibao: common.throttleFunc(function (e) {
    wx.navigateTo({
      url: '/pages/tibaoList/tibaoList',
    })
  }),
  // 跳转押金
  yajin: common.throttleFunc(function (e) {
    const type = wx.getStorageSync('type')
    if (type==0) {
      const authFunction = wx.getStorageSync('authFunction')
      const index = authFunction.indexOf("3")
      if(index == -1) {
        wx.showToast({
          title: '暂无权限',
          icon: "none"
        })
        return
      } 
    }
    wx.navigateTo({
      url: '/pages/yajin/yajin',
    })
  }),
  // 跳转常见问题
  question: common.throttleFunc(function (e) {
    wx.navigateTo({
      url: '/pages/question/question',
    })
  }),
  // 跳转我的客服
  kefu: common.throttleFunc(function (e) {
    wx.navigateTo({
      url: '/pages/kefu/kefu',
    })
  }),
  // 跳转京天家人
  family: common.throttleFunc(function (e) {
    wx.navigateTo({
      url: '/pages/family/family',
    })
  }),
  // 跳转会员推荐
  tuijian: common.throttleFunc(function (e) {
    wx.navigateTo({
      url: '/pages/yjmx/yjmx',
    })
  }),
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  getShopSum() {
    let that = this
    api.get_cart({
      cityId: wx.getStorageSync("cityId"),
      userId: wx.getStorageSync("openId"),
      page: {}
    }).then(res => {
      let getSum = res.data.body.getSum;
      if (getSum > 0) {

        wx.setTabBarBadge({
          index: 3,
          text: getSum + '' //显示的内容 
        })
      } else {
        wx.hideTabBarRedDot({
          index: 3
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    let that = this
    if (wx.getStorageSync('codeNum') == 104) {
      //组件接口
      api.shopBack({
          cityId: wx.getStorageSync("cityId")
        })
        .then(res => {
          if (res.result && res.body.getShopInfo.length) {
            console.log(res)
            let len = res.body.getShopInfo.length - 1;
            let shopBack = res.body.getShopInfo[len]

            this.setData({
              shopBack,
              codeNum: wx.getStorageSync("codeNum")
            })
          }
        })
    }
    if (wx.getStorageSync('codeNum') == 99) {
      await that.getShopSum()


      //优惠卷数量
      api.discountUser({
        cityId: wx.getStorageSync("cityId"),
        status: 0
      }).then(res => {
        that.setData({
          discountNum: res
        })
      })
      api.get_cart({
        userId: wx.getStorageSync("openId"),
        cityId: wx.getStorageSync("cityId"),
        page: {}
      }).then(res => {

        if (res.data.result) {
          wx.setStorageSync("userMess", res.data.object)
          if(res.data.object.vipEndDate < Date.now()) {
            res.data.object.vipEndDate = 123
          }else{
            res.data.object.vipEndDate = time.formatTimeTwo(res.data.object.vipEndDate, 'Y/M/D')
          }
          that.setData({
            userMess: res.data.object
          })
        }
      })
      //角标
      api.getStatus({
        cityId: wx.getStorageSync("cityId")
      }).then(res => {
        if (res.result) {
          that.setData({
            storeName: wx.getStorageSync("storeName"),
            getStatus: res.body.getStatus,
          })

        }
      })
    }
    that.setData({
      codeNum: wx.getStorageSync('codeNum'),
      tokenCode: wx.getStorageSync('token'),
      userMessage: wx.getStorageSync('userMessage'),
      vipFlag: wx.getStorageSync('vipFlag'),
      type: wx.getStorageSync("type"),
    })
    that.setData({
      city: that.data.city,
      avatarUrl: that.data.avatarUrl,
      province: that.data.province,
      gender: that.data.gender,
      nickName: that.data.nickName,
    })


    api.shopType({}).then(res => {
        if (res.result) {
          this.setData({
            storeChoose: res.object,
          })
        }
      }),




      that.setData({
        isInit: true
      })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  onShareAppMessage() {
    return {
      title: '京天鲜生, 生鲜管家',
      path: '/pages/index/index',
      imageUrl: '../../images/share.jpeg', // 可以更换分享的图片
    }
  }
})